<!-- 
 我的总结：FormData注意要大写
 fetch返回的是一个promise前面也要加上await
-->

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <img src="" alt="" id="imgAvatar">
    <input type="file" id="avatar">
    <button>上传</button>
    <script>
        const img = document.getElementById('imgAvatar');
        console.dir(img);


        async function upload() {
            const inp = document.getElementById('avatar')
            console.log(inp.files);
            if (inp.files.length === 0) {
                return alert('请选择需要上传的文件')
            }

            const formData = new FormData()   //FormData注意大写,构建请求体
            formData.append('imagefile', inp.files[0])

            const url = 'http://localhost:9527/api/upload';
            const resp = await fetch(url, {
                method: 'POST',
                body: formData   //formData会自动修改请求头的 content-type为 multipart/form-data;
            })

            const result = await resp.json()
            return result
        }

        function makeImageResponsive(img) {
            img.style.maxWidth = '100%';      // 最大宽度为父容器宽度
            img.style.height = 'auto';        // 高度自动，保持比例
            img.style.display = 'block';      // 避免图片下方有空白间隙
        }



        // document.querySelector('button').onclick = async () => {
        //     const result = await upload()
        //     img.src = result.path
        //     makeImageResponsive(img)

        // }


        document.querySelector('button').onclick = () => {
            upload()
                .then(result => {
                    img.src = result.path
                    makeImageResponsive(img)
                })



        }
    </script>
</body>

</html>